/**
 * 
 */
package com.whm.comtest.ftp;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPConnectionClosedException;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.net.io.CopyStreamEvent;
import org.apache.commons.net.io.CopyStreamListener;

import android.util.Log;

/**
 * @author hamwang
 * 
 */
public class FtpUtil {
	private static final String TAG = "FtpUtil";
	
	public interface ProgressListener {
		void notifyProgress(int nProgress);
	}

	public static void upLoad(final String strFileName, final String strServerAddress, final int nPort,	final String strUserName, final String strPassword) {
		transfer(false, strFileName,strServerAddress, nPort, strUserName, strPassword,null);
	}
	public static void downLoad(final String strFileName, final String strServerAddress, final int nPort,	final String strUserName, final String strPassword) {
		transfer(true, strFileName,strServerAddress, nPort, strUserName, strPassword,null);
	}
	
	public static void upLoad(final String strFileName, final String strServerAddress, final int nPort,	final String strUserName, final String strPassword,final ProgressListener progressListener) {
		transfer(false, strFileName,strServerAddress, nPort, strUserName, strPassword,progressListener);
	}
	public static void downLoad(final String strFileName, final String strServerAddress, final int nPort,	final String strUserName, final String strPassword,final ProgressListener progressListener) {
		transfer(true, strFileName,strServerAddress, nPort, strUserName, strPassword,progressListener);
	}
	
	private static void transfer(boolean bDownload, final String strFileName, final String strServerAddress, final int nPort,	final String strUserName, final String strPassword, final ProgressListener progressListener) {

		FTPClient ftp = new FTPClient();

		// connect to the ftp server
		try {
			int reply;
			if (nPort > 0) {
				ftp.connect(strServerAddress, nPort);
			} else {
				ftp.connect(strServerAddress);
			}
			System.out.println("Connected to " + strServerAddress + " on "
					+ (nPort > 0 ? nPort : ftp.getDefaultPort()));

			// After connection attempt, you should check the reply code to
			// verify
			// success.
			reply = ftp.getReplyCode();

			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				System.err.println("FTP server refused connection.");
				//System.exit(1);
			}
		}
		catch (IOException e) {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException f) {
					// do nothing
				}
			}
			System.err.println("Could not connect to server.");
			e.printStackTrace();
			//System.exit(1);
		}

		// upload file
		boolean error = false;
__main:
		
		try {
			
			// login
			if(!ftp.login(strUserName, strPassword))
			  {
	                ftp.logout();
	                error = true;
	                break __main;
	          }
			
			// set client attributes
			ftp.setFileType(FTP.BINARY_FILE_TYPE);
			
			// set copy stream listener
			ftp.setCopyStreamListener(new CopyStreamListener() {
				int m_nPercentage = 0 ;
				@Override
				public void bytesTransferred(long longTotalBytesTransfered, int nBytesTansfered, long longStreamSize) {
					// TODO Auto-generated method stub
					Log.i(TAG,"bytesTransfered -" + "totla transfered: " +longTotalBytesTransfered + " bytesTransfered: "+nBytesTansfered + " stream size: " + longStreamSize );
					if(progressListener != null){
						progressListener.notifyProgress((++m_nPercentage)%100);
					}
				}
				
				@Override
				public void bytesTransferred(CopyStreamEvent event) {
					// TODO Auto-generated method stub
					bytesTransferred(event.getTotalBytesTransferred(), event.getBytesTransferred(), event.getStreamSize());
				}
			});
			
			if(bDownload){
				OutputStream output= new FileOutputStream(strFileName);
				
				int nNameIndex = strFileName.lastIndexOf("/")== -1 ? 0 : strFileName.lastIndexOf("/") ;
				ftp.retrieveFile(strFileName.substring(nNameIndex),output);
				output.close();
			}
			else {
				
				InputStream input = new FileInputStream(strFileName);
				int nNameIndex = strFileName.lastIndexOf("/")== -1 ? 0 : strFileName.lastIndexOf("/") ; 
				ftp.storeFile(strFileName.substring(nNameIndex),input);
				input.close();
			}
			
			
			
			ftp.noop();
			ftp.logout();
		}
		catch (FTPConnectionClosedException e)
        {
            error = true;
            System.err.println("Server closed connection.");
        	Log.i(TAG,e.toString());
        }
        catch (IOException e)
        {
            error = true;
        	Log.i(TAG,e.toString());
        }
        catch(Exception e){
        	error = true;
			Log.i(TAG,e.toString());
		}
	    finally
        {
            if (ftp.isConnected())
            {
                try
                {
                    ftp.disconnect();
                }
                catch (IOException f)
                {
                    // do nothing
                }
            }
        }
		
		//System.exit(error? 0 : 1);
		//http://fallenlord.blogbus.com/logs/113793095.html
		
	}
	public static final void main(String[] args){
		
		FtpUtil.upLoad("d:/aa.jpg", "www.ningshang99.com", 21, "ubuntu","gyxmmb@23" );
	}
}
